package com.example.demo.service.serviceImpl;

import com.example.demo.dao.LiveDao;
import com.example.demo.entity.Live;
import com.example.demo.service.LiveService;
import com.example.demo.util.Result;
import com.example.demo.util.ResultSubmit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * (Live)表服务实现类
 *
 * @author makejava
 * @since 2025-04-22 14:35:14
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class LiveServiceImpl implements LiveService {
    @Resource
    private LiveDao dao;

    @Override
    public Result selectAllLive(Live live) {
        return ResultSubmit.success(dao.queryAll(live));
    }

    @Override
    public Result settlementLive(Live live) {
        live = dao.queryAll(live).get(0);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date liveTime = df.parse(live.getLiveTime());//入住时间
            Date cancelTime=df.parse(live.getCancelTime());//退房时间
            Long num= cancelTime.getTime()-liveTime.getTime();//时间戳相差的毫秒数
            BigDecimal day = BigDecimal.valueOf(num/24/60/60/1000).add(BigDecimal.ONE);//除以一天的毫秒数计算天数
            live.setLiveAmount(day.multiply(live.getRoomPrice()));//并计算金额
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = dao.updateLive(live);
        int j = dao.insertLive(live);
        if(i == 1 && j == 1){
            return ResultSubmit.success();
        }else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.fail();
        }
    }

    @Override
    public Result collectionLive(Live live) {
        live = dao.queryAll(live).get(0);
        int i = dao.updateLive(live);
        live.setCollectionIdentity("已收款");
        int j = dao.insertLive(live);
        if(i == 1 && j == 1){
            return ResultSubmit.success();
        }else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.fail();
        }
    }
}
